package com.danhuang.cloud.danhuangfile.config;

import io.minio.*;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.InputStream;

@Component
public class MinioTemplate implements InitializingBean {

    @Resource
    private MinioProperties minioProperties;

    private MinioClient client;


    public boolean exist(String bucket) throws Exception{
        return client.bucketExists(new BucketExistsArgs.Builder().bucket(bucket).build());
    }

    public void makeBucket(String bucket)throws Exception{
        client.makeBucket( MakeBucketArgs.builder().bucket(bucket).build());
    }

    public void fileUploader(String bucket, String path, InputStream inputStream)throws Exception{
        client.putObject( PutObjectArgs.builder().bucket(bucket).object(path).stream(inputStream, inputStream.available(), -1).build());
    }

    public InputStream fileDowner(String bucket, String path)throws Exception{
        return client.getObject(GetObjectArgs.builder().bucket(bucket).object(path).build());
    }



    @Override
    public void afterPropertiesSet() throws Exception {
        this.client = new MinioClient.Builder()
                .endpoint(minioProperties.getEndpoint())
                .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey()).build();
    }
}
